/*
 * sessionmgr.cpp
 *
 *  Created on: 2019-1-12
 *      Author: work
 */

#include <dm/session/sessionmgr.hpp>

#include <dm/session/modgen.hpp>
#include <dm/os/log/logger.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>

namespace dm{
namespace session{

static const char* logModule = "CSessionMgr.session.dm";

using namespace boost::interprocess;

CSessionMgr::CSessionMgr(){
	log().debug(THISMODULE "创建系统对象 Size=%d",Size);
}

CSessionMgr* CSessionMgr::ins(){
	static CSessionMgr* i = NULL;

	if( i==NULL ){
		permissions p;
		p.set_unrestricted();
		try{
			static managed_shared_memory memmgr(open_or_create,logModule,sizeof(CSessionMgr)+1024,0,p);
			i = memmgr.find_or_construct<CSessionMgr>(unique_instance)();
		}catch( interprocess_exception& e ){
			log().error(STATICMODULE "内存分配失败%s",e.what());
		}
	}

	return i;
}

bool CSessionMgr::reset(){
	try{
		log().warnning(THISMODULE "移除系统对象");
		shared_memory_object::remove(logModule);
		return true;
	}catch( interprocess_exception& e ){
		log().error(THISMODULE "内存删除失败%s",e.what());
		return false;
	}
}

CSession* CSessionMgr::getNew( userid_t userId,dm::CTimeStamp::s_t aliveSec ){
	dm::CTimeStamp n = dm::CTimeStamp::cur();
	for( int i=0;i<Size;++i ){
		if( m_session[i].init(userId,n,aliveSec) ){
			log().debug(THISMODULE "分配新的会话[%d]%llX",i,m_session[i].mod());
			return m_session + i;
		}
	}

	log().warnning(THISMODULE "分配新的会话失败");

	return NULL;
}

CSession* CSessionMgr::get( userid_t userId,mod_t mod,dm::CTimeStamp::s_t aliveSecs ){
	dm::CTimeStamp n = dm::CTimeStamp::cur();
	for( int i=0;i<Size;++i ){
		if( m_session[i].update(mod,userId,n,aliveSecs) )
			return m_session+i;
	}

	return NULL;
}

void CSessionMgr::free( userid_t userId,mod_t mod ){
	for( int i=0;i<Size;++i ){
		if( m_session[i].free(mod,userId) )
			return;
	}
}

int CSessionMgr::maxSize()const{
	return Size;
}

int CSessionMgr::emptySize()const{
	int i = 0;
	dm::CTimeStamp n = dm::CTimeStamp::cur();
	for( int i=0;i<Size;++i ){
		if( m_session[i].isIdle(n) )
			++i;
	}

	return i;
}

}
}
